#include <iostream>
#include <brpc/server.h>
#include <butil/logging.h>
#include "main.pb.h"

class EchoServiceImpl: public example::EchoService
{
public:
    EchoServiceImpl()
    {}

    ~EchoServiceImpl()
    {}

    //收到请求后调用处理
    virtual void Echo(google::protobuf::RpcController* controller,
                       const ::example::EchoRequest* request,
                       ::example::EchoResponse* response,
                       ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done); //智能指针管理资源，析构的时候调用done->run()
        std::cout << "收到消息" << request->message() << std::endl;
        std::string str = request->message() + "-响应-";
        response->set_message(str);
        //done->run()
    }
};


int main()
{
    //关闭brpc的默认日志输出
    logging::LoggingSettings settings;
    settings.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
    logging::InitLogging(settings);

    //创建子类继承于EchoService, 并且实现rpc调用的业务功能
    //构造服务器对象
    brpc::Server server;
    //向服务器对象中，新增EchoService服务
    EchoServiceImpl echoService;
    int ret = server.AddService(&echoService, brpc::ServiceOwnership::SERVER_DOESNT_OWN_SERVICE);
    if(ret == -1)
    {
        std::cout << "添加服务失败" << std::endl;
        return -1;
    }

    brpc::ServerOptions options;
    options.idle_timeout_sec = -1 ; //连接的空闲超时时间，超时后连接被关闭
    options.num_threads = 1;  //io的线程数量
    int n = server.Start(8080, &options); //8080端口
    if(n == -1)
    {
        std::cout << "启动服务器失败" << std::endl;
        return -1;
    }

    server.RunUntilAskedToQuit(); //休眠等到运行结束
    return 0;
}